package com.xindaoapp.happypet.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bulletnoid.android.widget.StaggeredGridView.StaggeredGridView;
import com.bulletnoid.android.widget.StaggeredGridView.StaggeredGridView.OnLoadmoreListener;
import com.bulletnoid.android.widget.StaggeredGridView.StaggeredGridView.OnScrollListener1;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshStaggeredGridView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.activity.HomeBannerDetailActivity;
import com.xindaoapp.happypet.bean.HomeBanner;
import com.xindaoapp.happypet.bean.HomeBannerEntity;
import com.xindaoapp.happypet.bean.MainZuixinData;
import com.xindaoapp.happypet.bean.MainZuixinData.MainTiezi;
import com.xindaoapp.happypet.ui.SplashPictureActivity2.LoadType;
import com.xindaoapp.happypet.utils.CommonParameter;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.utils.MoccaPreferences;
import com.xindaoapp.happypet.view.RollViewPager;
import com.xindaoapp.happypet.view.RoundImageView2;

/**
 * @author Yangqing 首页美图fragment
 * 
 */
public class BeautifulFragment extends BaseFragment {

    private PullToRefreshStaggeredGridView pullRefreshStagGridView;
    private ArrayList<View> dotLists;
    private View mHeadView;
    private LinearLayout mViewPagerContainer;
    private TextView mTvDescription;
    private LinearLayout mPointsContainer;
    private int currentPage = 1;
    private int totalCount;
    private final List<MainTiezi> mList = new ArrayList<MainZuixinData.MainTiezi>();
    private MyAdapter mAdapter;
    private List<HomeBanner> mBanners;
    private RollViewPager mRollViewPager;

    private boolean isLoadFirst = true;// 是否为第一次加载

    Map<Integer, Boolean> isZanMap = new HashMap<Integer, Boolean>();
    Map<Integer, ImageView> imgMap = new HashMap<Integer, ImageView>();

    private final int position = 0;

    // 是否为正在加载更多
    // private boolean isLoadingMore = false;


    public static Fragment newInstance() {
        Fragment fragment = new BeautifulFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return mView = inflater.inflate(R.layout.layout_beautifual, null);
    }


    @Override
    protected void initViews() {
        super.initViews();
        pullRefreshStagGridView =
                (PullToRefreshStaggeredGridView) mView.findViewById(R.id.mListView);
        pullRefreshStagGridView.getRefreshableView().setColumnCount(2);
        // 头部banner数据
        // mHeadView = LayoutInflater.from(mContext).inflate(R.layout.head_zuixinfragment, null);
        // mViewPagerContainer = (LinearLayout) mHeadView.findViewById(R.id.viewpager1);
        // mViewPagerContainer.setLayoutParams(new RelativeLayout.LayoutParams(
        // LayoutParams.MATCH_PARENT, CommonParameter.sScreenWidth * 248 / 640));
        // mTvDescription = (TextView) mHeadView.findViewById(R.id.tv_image_description1);
        // mPointsContainer = (LinearLayout) mHeadView.findViewById(R.id.ll_points1);

        mFootView = LayoutInflater.from(mContext).inflate(R.layout.item_loading, null);
        // retryFootview = View.inflate(mContext, R.layout.item_failed, null);
        mHeadView = new ImageView(mContext);
        pullRefreshStagGridView.getRefreshableView().setHeaderView(mHeadView);
        pullRefreshStagGridView.getRefreshableView().setFooterView(mFootView);
        back_top = mView.findViewById(R.id.back_top);


        pullRefreshStagGridView.setVisibility(View.GONE);



        pullRefreshStagGridView.setOnRefreshListener(new OnRefreshListener<StaggeredGridView>() {

            @Override
            public void onRefresh(PullToRefreshBase<StaggeredGridView> refreshView) {
                pullRefreshStagGridView.getRefreshableView().setColumnCount(2);
                if (CommonUtil.isNetworkAvailable(mContext) == 0) {
                    Toast.makeText(mContext, "当前网络不可用", Toast.LENGTH_SHORT).show();
                    pullRefreshStagGridView.onRefreshComplete();
                    return;
                }
                currentPage = 1;
                getGridViewData(LoadType.PULLDOWN);
            }
        });

        pullRefreshStagGridView.setOnLoadmoreListener(new OnLoadmoreListener() {

            @Override
            public void onLoadmore() {
                if (CommonUtil.isNetworkAvailable(mContext) == 0) {
                    Toast.makeText(mContext, "当前网络不可用", Toast.LENGTH_SHORT).show();
                    pullRefreshStagGridView.onRefreshComplete();
                    pullRefreshStagGridView.onLoadSuccess();
                    pullRefreshStagGridView.getRefreshableView().loadlock = false;
                    // mAdapter.notifyDataSetChanged();
                    return;
                }
                if (totalCount > ((currentPage - 1) * 16)) {
                    currentPage++;
                    getGridViewData(LoadType.PULLUP);
                } else {
                    pullRefreshStagGridView.getRefreshableView().getFooterView()
                            .setVisibility(View.GONE);
                    // Toast.makeText(mContext, "没有更多数据了", Toast.LENGTH_SHORT).show();
                }
                pullRefreshStagGridView.onRefreshComplete();
            }
        });


        pullRefreshStagGridView.getRefreshableView().setOnScrollListener1(new OnScrollListener1() {

            @Override
            public void onScoll(int first) {

            }
        });
    }

    @Override
    protected void initEvents() {
        super.initEvents();
        back_top.setOnClickListener(mOnClickListener);

        // retryFootview.setOnClickListener(new OnClickListener() {
        // @Override
        // public void onClick(View v) {
        // loadDatas();
        // }
        // });

    }

    private final OnClickListener mOnClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.back_top:
                    pullRefreshStagGridView.getRefreshableView().setSelectionToTop();
                    break;
            }
        }
    };



    @Override
    protected void loadDatas() {
        super.loadDatas();
        // getBannderData();
        getGridViewData(LoadType.PULLDOWN);
    }

    private void getBannderData() {
        getMoccaApi().getIndexBanner("index", new IRequest<HomeBannerEntity>() {
            @Override
            public void request(HomeBannerEntity t) {

                if (null != t) {
                    onDataArrived(true);
                    if (t.getArray().size() == 0) {
                        // onDataArrivedEmpty();
                    } else {
                        mBanners = t.getArray();
                        prepareViewPage(mContext, t.getArray());
                    }
                } else {
                    onDataArrived(false);
                }
                // mPullToRefreshListView.onRefreshComplete();

            }
        });
    }


    private final List<Integer> Tids = new ArrayList<Integer>();
    private View mFootView;
    private View back_top;

    // private View retryFootview;

    private void getGridViewData(final LoadType loadType) {
        getMoccaApi().getBeautifulList(currentPage, 16, new IRequest<MainZuixinData>() {

            @Override
            public void request(MainZuixinData t) {
                pullRefreshStagGridView.setVisibility(View.VISIBLE);
                if (null != t) {
                    isLoadFirst = false;
                    onDataArrived(true);
                    if (t.array.size() == 0) {
                        onDataArrivedEmpty();
                    } else {
                        MoccaPreferences.MeiTuTid.put(t.array.get(0).tid);
                        totalCount = Integer.parseInt(t.total);
                        if (loadType == LoadType.PULLDOWN) {
                            if (mList != null)
                                mList.clear();
                        }

                        // 帖子去重
                        int i = 1;
                        long currentTimeMillis = System.currentTimeMillis();
                        // System.out.println("去重前时间：" + currentTimeMillis);
                        if (loadType == loadType.PULLUP) {
                            if (Tids != null && Tids.size() > 30) {
                                Tids.clear();
                            }
                            List<MainTiezi> array = t.array;
                            for (MainTiezi tiezi : array) {
                                // System.out.println("第" + i + "张mHeight = "
                                // + tiezi.pics.get(0).height + "mWdith = "
                                // + tiezi.pics.get(0).width + "--author:" + tiezi.author);
                                i++;
                                int tieziId = Integer.parseInt(tiezi.tid);
                                for (Integer mTid : Tids) {
                                    if (tieziId == mTid) {
                                        try {
                                            t.array.remove(tiezi);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            }
                            // System.out.println("去重耗时："
                            // + (System.currentTimeMillis() - currentTimeMillis));
                        }

                        mList.addAll(t.array);
                        if (mAdapter == null) {
                            mAdapter = new MyAdapter();
                            pullRefreshStagGridView.getRefreshableView().setAdapter(mAdapter);
                        }
                        mAdapter.notifyDataSetChanged();
                    }
                } else {
                    // 第一次loading失败时，显示loading失败页面，否则不显示
                    if (isLoadFirst)
                        onDataArrived(false);
                    // pullRefreshStagGridView.getRefreshableView().getFooterView()
                    // .setVisibility(View.VISIBLE);
                    if (loadType == LoadType.PULLUP) {
                        currentPage--;
                        pullRefreshStagGridView.getRefreshableView().loadlock = false;
                    }
                }
                pullRefreshStagGridView.onRefreshComplete();
            }
        });

    }

    class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            if (mList == null) {
                return 0;
            } else {
                return mList.size();
            }
        }

        @Override
        public Object getItem(int arg0) {
            return mList.get(arg0);
        }

        @Override
        public long getItemId(int arg0) {
            return arg0;
        }


        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            if (position > 20 && back_top != null) {
                back_top.setVisibility(View.VISIBLE);
            } else {
                back_top.setVisibility(View.GONE);
            }

            ViewHolder holder;

            if (convertView == null) {
                holder = new ViewHolder();
                convertView =
                        LayoutInflater.from(mContext).inflate(R.layout.item_beautiful_new, null);
                holder.img1 = (RoundImageView2) convertView.findViewById(R.id.img1);
                holder.title1 = (TextView) convertView.findViewById(R.id.title1);
                holder.iv_zan1 = (ImageView) convertView.findViewById(R.id.iv_zan1);
                holder.tv_zancount1 = (TextView) convertView.findViewById(R.id.tv_zancount1);
                holder.rl_tpcount1 = (RelativeLayout) convertView.findViewById(R.id.rl_tpcount1);
                holder.tv_tpcount1 = (TextView) convertView.findViewById(R.id.tv_tpcount1);
                // holder.rl1 = (RelativeLayout) convertView.findViewById(R.id.rl1);
                holder.rl_black = (RelativeLayout) convertView.findViewById(R.id.rl_black);
                holder.img1.setScaleType(ScaleType.CENTER_CROP);
                holder.rl_black.getBackground().setAlpha(120);
                holder.tv_tpcount1.getBackground().setAlpha(120);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            imgMap.put(position, holder.iv_zan1);

            final MainTiezi value = mList.get(position);
            Integer mTid = 0;
            try {
                mTid = Integer.parseInt(value.tid);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            Tids.add(mTid);

            int mHeight = 50;
            try {
                mHeight = Integer.parseInt(value.pics.get(0).height);
            } catch (Exception e) {
                e.printStackTrace();
            }
            int mWidth = 50;
            try {
                mWidth = Integer.parseInt(value.pics.get(0).width);
            } catch (Exception e) {
                e.printStackTrace();
            }
            // android.view.ViewGroup.LayoutParams layoutParams2 = holder.rl1.getLayoutParams();
            // layoutParams2.width = CommonParameter.sScreenWidth / 2;
            // layoutParams2.height =
            // (int) ((float) (CommonParameter.sScreenWidth / 2 / mWidth) * mHeight);
            // holder.rl1.setLayoutParams(layoutParams2);
            holder.img1.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                    (int) ((float) CommonParameter.sScreenWidth / 2 / mWidth * mHeight)));

            // android.view.ViewGroup.LayoutParams layoutParams = holder.img1.getLayoutParams();
            // layoutParams.width = CommonParameter.sScreenWidth / 2;
            // layoutParams.height = (CommonParameter.sScreenWidth / 2 / mWidth * mHeight);
            // holder.img1.setLayoutParams(layoutParams);
            holder.img1.setScaleType(ScaleType.FIT_XY);

            if (mList.get(position).pics.size() > 0) {

                ImageLoader.getInstance().displayImage(mList.get(position).pics.get(0).url,
                        holder.img1);
            } else {
                holder.img1.setBackgroundResource(R.drawable.picture_loading);
            }
            if (Integer.parseInt(mList.get(position).picnum) > 0) {
                holder.rl_tpcount1.setVisibility(View.VISIBLE);
                holder.tv_tpcount1.setText(mList.get(position).picnum + "张");
            } else {
                holder.rl_tpcount1.setVisibility(View.GONE);
            }
            holder.title1.setText(mList.get(position).author);
            holder.tv_zancount1
                    .setText(Integer.parseInt(mList.get(position).recommend_add) > 0 ? mList
                            .get(position).recommend_add : "赞");

            if (mList.get(position).recommendmy.equals("1")) {
                isZanMap.put(position, true);
                holder.iv_zan1.setImageResource(R.drawable.dianzan_c);
            } else {
                isZanMap.put(position, false);
                holder.iv_zan1.setImageResource(R.drawable.dianzan_n);
            }


            // 点赞,王总不要了!!!
            // holder.iv_zan1.setOnClickListener(new OnClickListener() {
            // @Override
            // public void onClick(View v) {
            // CommonUtil.goZan(getActivity(), isZanMap, imgMap, position, value);
            // }
            // });

            convertView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    String tid = "";
                    try {
                        tid = mList.get(position).tid;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    Intent intent =
                            new Intent(mContext, com.xindaoapp.happypet.ui.PostDetailActivity.class);
                    intent.putExtra(Constants.KEY_POST_TID, tid);
                    intent.putExtra(Constants.KEY_FROM_PAGE, 1);
                    if (!TextUtils.isEmpty(tid)) {
                        mContext.startActivity(intent);
                    }
                }
            });
            return convertView;
        }
    }

    class ViewHolder {
        // private RelativeLayout rl1;
        private RelativeLayout rl_black;
        private RelativeLayout rl_tpcount1;
        private RoundImageView2 img1;
        private TextView title1;
        private ImageView iv_zan1;
        private TextView tv_zancount1;
        private TextView tv_tpcount1;
    }


    public void prepareViewPage(final Context context, final List<HomeBanner> list) {
        List<String> titleList = new ArrayList<String>();
        List<String> imageUrlList = new ArrayList<String>();
        for (HomeBanner homeBanner : list) {
            titleList.add(homeBanner.getTitle());
            imageUrlList.add(homeBanner.getCoverpath());
        }
        initDots(list.size());
        mRollViewPager =
                new RollViewPager(context, dotLists, R.drawable.point_normal,
                        R.drawable.point_enable, new RollViewPager.MyOnTouchCllickCallBack() {
                            @Override
                            public void OnTouchCllick(int position) {
                                String type = list.get(position % list.size()).getType();
                                if (type.equals("web")) {// 跳转到详情
                                    Intent intent1 =
                                            new Intent(context, HomeBannerDetailActivity.class);
                                    intent1.putExtra("url", list.get(position % list.size())
                                            .getLink());
                                    context.startActivity(intent1);
                                    getActivity().overridePendingTransition(
                                            R.anim.new_dync_in_from_right,
                                            R.anim.new_dync_out_to_left);
                                } else if (type.equals("appthread")) {// 跳转到帖子详情
                                    Intent intent2 = new Intent(context, PostDetailActivity.class);
                                    intent2.putExtra("postID", list.get(position % list.size())
                                            .getLink());
                                    context.startActivity(intent2);
                                    getActivity().overridePendingTransition(
                                            R.anim.new_dync_in_from_right,
                                            R.anim.new_dync_out_to_left);
                                }
                            }
                        });
        mRollViewPager.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                CommonParameter.sScreenWidth * 248 / 640));
        mRollViewPager.setTitle(mTvDescription, titleList);
        mRollViewPager.setImageUrl(imageUrlList);
        mRollViewPager.startRoll();
        mViewPagerContainer.removeAllViews();
        mViewPagerContainer.addView(mRollViewPager);

    }

    private void initDots(int size) {
        dotLists = new ArrayList<View>();
        mPointsContainer.removeAllViews();
        for (int i = 0; i < size; i++) {
            LinearLayout.LayoutParams layoutParams =
                    new LinearLayout.LayoutParams(CommonUtil.dip2px(mContext, 5),
                            CommonUtil.dip2px(mContext, 5));
            layoutParams.setMargins(5, 0, 5, 8);
            ImageView m = new ImageView(mContext);
            if (i == 0) {
                m.setBackgroundResource(R.drawable.point_enable);
            } else {
                m.setBackgroundResource(R.drawable.point_normal);
            }
            m.setLayoutParams(layoutParams);
            dotLists.add(m);
            mPointsContainer.addView(m);
        }
    }


}
